package com.jisu.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jisu.common.ResultVo;
import com.jisu.dto.PageQueryDTO;
import com.jisu.dto.UserDTO;
import com.jisu.dto.UserQueryDTO;
import com.jisu.pojo.User;
import com.jisu.service.UserService;
import com.jisu.utils.JWTUtil;
import com.lingnan.feign.OssServiceClient;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
public class UserController {

    @Autowired
    private OssServiceClient ossServiceClient;


    @Autowired
    private UserService userService;

    @Value("${winter.token-secret}")
    private String secret;

    @PostMapping("/login")
    public ResultVo<Map<String, Object>> login(@RequestParam String userAccountNumber, @RequestParam String userPassword) {
        User userDB = userService.login(userAccountNumber, userPassword); // 确保 service 实现了 login 方法

        HashMap<String, String> payload = new HashMap<>();
        payload.put("id", userDB.getUserId().toString());
        payload.put("userAccountNumber", userDB.getUserAccountNumber());

        String token = JWTUtil.getToken(payload);

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", userDB); // 返回用户信息
        return ResultVo.success("登录成功", result);
    }

    @GetMapping("/verify")
    public ResultVo<?> verifyToken(@RequestHeader("Authorization") String token) {
        if (JWTUtil.verify(token)) {
            return ResultVo.success("验证通过");
        } else {
            return ResultVo.fail("Token无效");
        }
    }

    @GetMapping("/profile")
    public ResultVo<User> getProfile(HttpServletRequest request) {
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(request.getHeader("Authorization"));
        String username = decodedJWT.getClaim("username").asString();
        User user = userService.getByAccountNumber(username);
        return ResultVo.success("获取成功", user);
    }




    // 新增用户
    @PostMapping("/addUser")
    public ResultVo<Boolean> addUser(@RequestBody User user) {
        // 自动生成用户名：用户 + 8位随机数字
        if (user.getUserName() == null || user.getUserName().isEmpty()) {
            String randomNumbers = String.format("%08d", new Random().nextInt(100000000));
            user.setUserName("用户" + randomNumbers);
        }

        user.setState(1);

        if (user.getCreateTime() == null) {
            user.setCreateTime(LocalDateTime.now());
        }
        user.setUpdateTime(LocalDateTime.now());

        // 检查用户账号或手机号是否已存在
        String conflictField = userService.checkUserAccountOrPhoneExists(user.getUserAccountNumber(), user.getPhone());
        if (conflictField != null) {
            return ResultVo.fail(conflictField.equals("userAccountNumber") ? "用户账号已存在" : "手机号已存在", false);
        }

        // 插入用户
        if (userService.save(user)) {
            return ResultVo.success("注册成功", true);
        } else {
            return ResultVo.fail("注册失败", false);
        }
    }



    // 批量删除用户（通过路径参数传入多个 ID）
    @DeleteMapping("/deleteUserByIds/{ids}")
    public ResultVo<Boolean> deleteUser(@PathVariable List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return ResultVo.fail("未选中用户！");
        }

        try {
            boolean deleteRows = userService.removeBatchByIds(ids);
            if (deleteRows) {
                return ResultVo.success("删除成功", true);
            } else {
                return ResultVo.fail("删除失败", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.fail("未知错误", false);
        }
    }

//    // 更新用户信息（根据路径中的 ID 更新指定用户）
//    @PutMapping("/updateUserById/{id}")
//    public ResultVo<Boolean> updateUserById(@PathVariable Long id, @RequestBody UserDTO userDTO) {
//        User existingUser = userService.getById(id);
//        if (existingUser == null) {
//            return ResultVo.fail("用户不存在");
//        }
//
//
//        // 构造要更新的 User 对象
//        User user = new User();
//        user.setUserId(id); // ⚠️ 显式指定主键，避免被覆盖
//        user.setUpdateTime(LocalDateTime.now());
//
//        // 拷贝属性（可使用 BeanUtils.copyProperties）
//        BeanUtils.copyProperties(userDTO,user);
//        System.out.println(user);
//
//        try {
//            boolean result = userService.updateById(user);
//            if (result) {
//                return ResultVo.success("更新成功", true);
//            } else {
//                return ResultVo.fail("更新失败");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultVo.fail("未知错误", false);
//        }
//    }

    @PutMapping("/updateUserById/{id}")
    public ResultVo<User> updateUserById(
            @PathVariable Long id,
            @RequestPart("user") UserDTO userDTO,
            @RequestPart(value = "avatar", required = false) MultipartFile avatarFile) {

        User existingUser = userService.getById(id);
        if (existingUser == null) {
            return ResultVo.fail("用户不存在");
        }

        User user = new User();
        user.setUserId(id);
        user.setUpdateTime(LocalDateTime.now());

        BeanUtils.copyProperties(userDTO, user);

        // 如果有上传头像，调用 OSS 服务上传
        if (avatarFile != null && !avatarFile.isEmpty()) {
            try {
                String avatarUrl = ossServiceClient.uploadFile(avatarFile);
                System.out.println("上传成功"+avatarUrl);
                user.setAvatarUrl(avatarUrl);
                System.out.println("修改后的头像"+user.getAvatarUrl());
            } catch (Exception e) {
                e.printStackTrace();
                return ResultVo.fail("头像上传失败");
            }
        }

        System.out.println("修改后的用户"+user);

        try {
            boolean result = userService.updateById(user);
            if (result) {
                // 更新成功后，重新查询用户信息并返回
                User updatedUser = userService.getById(id);
                return ResultVo.success("更新成功", updatedUser);
            } else {
                return ResultVo.fail("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.fail("未知错误");
        }
    }




    // 根据 ID 查询用户信息
    @GetMapping("/getUserInfo")
    public ResultVo getUserInfo(@RequestParam("id") Long id) {
        User user = userService.getById(id);
        if (user != null) {
            return ResultVo.success("查询成功", user);
        } else {
            return ResultVo.fail("用户不存在");
        }
    }

//     多条件查询用户信息（支持模糊匹配、时间范围等）
    @GetMapping("/searchUsers")
    public ResultVo<List<User>> searchUsers(UserQueryDTO userQueryDTO) {
        List<User> users = userService.searchUsers(userQueryDTO);
        return ResultVo.success("查询成功", users);
    }


    @PostMapping("/getAllUsers")
    public ResultVo<IPage<User>> getAllUsers(@RequestBody PageQueryDTO pageQueryDTO) {


        IPage<User> userPage = userService.getUsersByPage(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());
        return ResultVo.success("查询成功", userPage);
    }







}
